<?php
namespace Modules\Payment\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Order\Entities\UnionOrder;
use \Modules\Order\Entities\BaseOrder as Order;

use Validator;
use ThrowException;
use Payment;
use Cache;
use Miniapp;
use SimpleXMLElement;

class ZhongjinCallbackController extends Controller
{
    // 中金支付回调
    public function pay(Request $req) 
    {
        $all = $req->all();

        $pay = Payment::ZhongjinPay('default', 'wechat');

        $data = $pay->checkCallbackData($req);
        if (!$data) {
            \Log::error('验签失败:');
            \Log::error($req->all());
            ThrowException::Conflict('Forbidden');
        }

        $simpleXML = new SimpleXMLElement($data);

        // 流水号
        $payNumber = $simpleXML->Body->PaymentNo;
        // 回调通知类型
        $txCode = $simpleXML->Head->TxCode;
        $status =  $simpleXML->Body->Status;

        switch ($txCode) {

            // 2108跳转支付
            case "2108": {

                // 订单号及订单
                $orderNumber = explode('_', $payNumber)[0];
                $order = Order::getDerivedOrder([
                    'number' => $orderNumber
                ]);

                if (!$order) {
                    \Log::error('中金支付回调失败，订单号不存在' . $payNumber);
                    return [];
                }

                if ($status == '20') {
                    // 支付成功
                    $options = $req->all();
                    $options['pay_type'] = 'zhongjin';
                    $options['pay_sub_type'] = '';

                    // 完成订单
                    $order->completePay($options);
                    \Log::error('完成订单支付');
                }
                elseif ($status == '30') {
                    // 支付失败
                }
                elseif ($status ==   '40') {
                    // 订单关闭
                }

                break;
            }
        }

        return $pay->success();
    }

}
